//
//  CouponsView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI

// 移除临时结构体定义，使用原始的数据类型

struct CouponsView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    @State private var showAlert = false
    @State private var alertMessage = ""

    @State private var selectedCoupon: Coupon?

    
    var userCoupons: [UserCoupon] {
        // 显示所有拥有的优惠券，包括已使用的和过期的（用于显示状态）
        return dataManager.currentUser?.ownedCoupons ?? []
    }
    
    var availableCoupons: [Coupon] {
        return dataManager.getAllCouponsForDisplay()
    }
    
    var sortedAvailableCoupons: [Coupon] {
        return dataManager.getSortedAvailableCoupons()
    }
    
    var body: some View {
        ZStack {
            // 背景渐变
            LinearGradient(
                colors: AppTheme.Colors.backgroundGradient,
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()
            
            VStack(spacing: 0) {
                // 自定义导航栏
                HStack {
                    Button(action: { dismiss() }) {
                        Image(systemName: "chevron.left")
                            .font(AppTheme.Typography.bodyMedium)
                            .foregroundColor(AppTheme.Colors.accentSecondary)
                    }
                    
                    Spacer()
                }
                .padding(.horizontal, 20)
                .padding(.top, 8)
                .padding(.bottom, 4)
                
                // 主要内容区域
                ZStack {
                    ScrollView {
                        VStack(spacing: 16) {
                            // 页面标题
                            HStack {
                                VStack(alignment: .leading, spacing: 6) {
                                    Text(dataManager.currentLanguage == "zh" ? AppStrings.Coupons.allCoupons : AppStrings.Coupons.allCouponsEn)
                                        .font(AppTheme.Typography.title2)
                                        .fontWeight(.bold)
                                        .foregroundColor(AppTheme.Colors.primaryText)
                                    
                                    Text(dataManager.currentLanguage == "zh" ? AppStrings.Coupons.chooseFavorite : AppStrings.Coupons.chooseFavoriteEn)
                                        .font(AppTheme.Typography.subheadline)
                                        .foregroundColor(AppTheme.Colors.primaryText.opacity(0.8))
                                }
                                
                                Spacer()
                            }
                            .padding(.horizontal, 20)
                            .padding(.top, 8)
                            
                            // 优惠券网格 - 每行一个卡片的布局设计
                            LazyVGrid(columns: [
                                GridItem(.flexible())
                            ], spacing: 8) {
                                // 显示所有可用的优惠券，未锁定的排在前面
                                ForEach(sortedAvailableCoupons, id: \.id) { coupon in
                                    staticCouponCard(coupon: coupon)
                                        .scaleEffect(1.0)
                                        .animation(.spring(response: 0.5, dampingFraction: 0.7, blendDuration: 0), value: coupon.id)
                                        .onTapGesture {
                                            selectedCoupon = coupon
                                        }
                                }
                            }
                            .padding(.horizontal, 20)

                        }
                        .padding(.bottom, 30)
                    }

                }
            }
        }
        .alert(AppStrings.Common.alert, isPresented: $showAlert) {
            Button(AppStrings.Common.confirm) { }
        } message: {
            Text(alertMessage)
        }
        .sheet(item: $selectedCoupon) { coupon in
            if #available(iOS 16.0, *) {
                CouponDetailSheet(coupon: coupon)
                    .environmentObject(dataManager)
            } else {
                // Fallback for iOS 15
                Text(AppStrings.Common.detailInfo)
                    .padding()
            }
        }
    }
    
    // 优惠券状态枚举
    enum CouponStatus {
        case available
        case expired
        case usedOnce
        case usedThisWeek
        case usedToday
        case usedThisMonth
        case usedThisYear
        case outsideTimeSlot
        case notActivated
        case requiresLogin
        case requiresMembershipLevel
    }
    
    // 检查优惠券激活状态
    private func checkCouponActivation(coupon: Coupon) -> CouponStatus {
        // 首先检查周频率优惠券的使用状态
        if coupon.usageFrequency == .weekly, let user = dataManager.currentUser {
            let calendar = Calendar.current
            if let currentWeekInterval = calendar.dateInterval(of: .weekOfYear, for: Date()) {
                // 检查本周是否已使用过此优惠券
                let usedThisWeek = user.couponUsageHistory.contains { record in
                    record.couponCode == coupon.code &&
                    currentWeekInterval.contains(record.usedDate)
                }
                
                // 如果本周已使用，返回usedThisWeek状态
                if usedThisWeek {
                    return .usedThisWeek
                }
            }
        }
        
        let unlockCondition = CouponConfig.UnlockConditions.getUnlockConditionType(
            for: coupon.code,
            user: dataManager.currentUser,
            dataManager: dataManager
        )
        
        switch unlockCondition {
        case .loginRequired:
            return .requiresLogin
        case .membershipLevel(_):
            return .requiresMembershipLevel
        case .timeSlotRestricted:
            return .outsideTimeSlot
        case .memberInfoComplete, .birthdayMonthRequired, .activationConditions(_), .expired, .inactive:
            return .notActivated
        case .usageLimitReached:
            return .usedOnce
        case .usageFrequencyReached:
            // 根据使用频率返回相应状态
            if let frequency = coupon.usageFrequency {
                switch frequency {
                case .once:
                    return .usedOnce
                case .daily:
                    return .usedToday
                case .weekly:
                    return .usedThisWeek
                case .monthly:
                    return .usedThisMonth
                case .yearly:
                    return .usedThisYear
                case .perOrder:
                    return .usedOnce
                }
            }
            return .usedOnce
        case .none:
            return .available
        }
    }
    
    // 检查优惠券状态
    private func getCouponStatus(coupon: Coupon, userCoupon: UserCoupon) -> CouponStatus {
        // 使用统一的解锁条件检查
        let unlockCondition = CouponConfig.UnlockConditions.getUnlockConditionType(
            for: coupon.code,
            user: dataManager.currentUser,
            dataManager: dataManager
        )
        
        // 将UnlockConditionType转换为CouponStatus
        switch unlockCondition {
        case .loginRequired:
            return .requiresLogin
        case .membershipLevel(_):
            return .requiresMembershipLevel
        case .timeSlotRestricted:
            return .outsideTimeSlot
        case .memberInfoComplete, .birthdayMonthRequired, .activationConditions(_):
            return .notActivated
        case .usageLimitReached:
            return .usedOnce
        case .usageFrequencyReached:
            // 根据使用频率返回相应状态
            if let frequency = coupon.usageFrequency {
                switch frequency {
                case .once:
                    return .usedOnce
                case .daily:
                    return .usedToday
                case .weekly:
                    return .usedThisWeek
                case .monthly:
                    return .usedThisMonth
                case .yearly:
                    return .usedThisYear
                case .perOrder:
                    return .usedOnce
                }
            }
            return .usedOnce
        case .expired:
            return .expired
        case .inactive:
            return .notActivated
        case .none:
            return .available
        }
    }
    
    // 决定是否显示优惠券
    private func shouldShowCoupon(coupon: Coupon, userCoupon: UserCoupon) -> Bool {
        let status = getCouponStatus(coupon: coupon, userCoupon: userCoupon)
        // 如果是一次性使用且已使用，则不显示
        if coupon.usageFrequency == .once && status == .usedOnce {
            return false
        }
        return true
    }
    
    // 静态礼券卡片组件（显示所有优惠券，包括已解锁和未解锁的）
    private func staticCouponCard(coupon: Coupon) -> some View {
        let isCashVoucher = coupon.isCashVoucher
        let displayTitle = coupon.formattedTitle(language: dataManager.currentLanguage)
        // 使用原始标题来获取数量，因为getCashVoucherQuantityByTitle需要完整标题来查找优惠券
        let quantity = isCashVoucher ? dataManager.getCashVoucherQuantityByTitle(coupon.title) : nil
        
        // 检查用户是否已解锁此优惠券
        let isUnlocked = dataManager.isUserCouponUnlocked(coupon)
        
        // 检查激活状态
        let activationStatus = checkCouponActivation(coupon: coupon)
        let isNotActivated = activationStatus != .available
        
        // 检查会员信息完善礼券的特殊状态
        let isMemberInfoCoupon = coupon.code == "MEMBER_INFO_COMPLETE"
        let isDisabled = isMemberInfoCoupon && !(dataManager.currentUser?.isMemberInfoComplete ?? false)
        let hasUserCoupon = dataManager.currentUser?.ownedCoupons.contains { $0.couponCode == coupon.code && !$0.isUsed && $0.expiryDate > Date() } ?? false
        
        // 如果是会员信息完善礼券且用户已拥有，则显示为可用状态
        // 如果用户未解锁此优惠券，则显示为禁用状态
        // 特殊处理：非运营时间的卡片视觉上不锁定，但点击时仍判断运营时间
        let isTimeSlotRestricted = activationStatus == .outsideTimeSlot
        let finalDisabled = !isUnlocked || (isMemberInfoCoupon ? (!hasUserCoupon && isDisabled) : (isNotActivated && !isTimeSlotRestricted))
        
        let baseCard = couponCard(
            tag: coupon.formatValue(), // 使用formatValue()生成的denomination标签用于badge定位
            tagColor: CouponTheme.getTagBackgroundColor(for: coupon.title),
            tagTextColor: CouponTheme.getTagTextColor(for: coupon.title),
            buttonColor: CouponTheme.getButtonBackgroundColor(for: coupon.title),
            buttonTextColor: CouponTheme.getButtonTextColor(for: coupon.title),
            value: coupon.formatValue(),
            title: coupon.formattedRemarks(language: dataManager.currentLanguage, displayTitle: displayTitle),
            validUntil: isUnlocked ? coupon.formatStaticValidUntil(language: dataManager.currentLanguage) : (dataManager.currentLanguage == "zh" ? "需要解锁" : "Requires Unlock"),
            gradientColors: CouponTheme.getGradientColors(for: coupon.title),
            showStrikethrough: finalDisabled,
            isDisabled: finalDisabled,
            quantity: quantity,
            originalTitle: coupon.title,
            onButtonTap: {
                handleButtonTap(for: coupon)
            }
        )
        
        // 统一所有锁定状态的视觉样式：如果优惠券被锁定（未解锁或未激活），都添加覆盖层
        if finalDisabled {
            return lockedCouponCard(baseCard: baseCard, coupon: coupon, activationStatus: activationStatus, isUnlocked: isUnlocked)
        } else {
            return AnyView(baseCard)
        }
    }
    
    // 统一的锁定优惠券卡片覆盖层
    private func lockedCouponCard(baseCard: some View, coupon: Coupon, activationStatus: CouponStatus, isUnlocked: Bool) -> AnyView {
        let statusText: String
        let statusTextEn: String
        
        // 统一的锁定原因显示逻辑
        if !isUnlocked {
            // 未解锁状态 - 统一显示解锁条件
            if coupon.requiresLogin && dataManager.currentUser == nil {
                statusText = "需要登录"
                statusTextEn = "Login Required"
            } else if let requiredLevelString = coupon.requiresMembershipLevel {
                // 根据requiresMembershipLevel（英文名称）找到对应的中文显示名称
                let displayName = MembershipLevel.getDisplayName(for: requiredLevelString, language: "zh") ?? requiredLevelString
                let englishName = MembershipLevel.getDisplayName(for: requiredLevelString, language: "en") ?? requiredLevelString
                statusText = "需要 \(displayName) 会员等级"
                statusTextEn = "Requires \(englishName) Membership"
            } else if coupon.code == "BIRTHDAY30" || coupon.code == "MEMBER_INFO_COMPLETE" {
                // 生日月专属礼券和会员信息完善礼券需要完善会员信息后才能解锁
                statusText = "完善会员信息后才能解锁"
                statusTextEn = "Complete member info to unlock"
            } else {
                // 统一显示：注册成为会员即可解锁
                statusText = "注册成为会员即可解锁"
                statusTextEn = "Register as member to unlock"
            }
        } else {
            // 已解锁但未激活状态 - 显示激活条件
            switch activationStatus {
            case .requiresLogin:
                statusText = "需要登录"
                statusTextEn = "Login Required"
            case .requiresMembershipLevel:
                if let requiredLevel = coupon.requiresMembershipLevel {
                    // 根据requiresMembershipLevel（英文名称）找到对应的中文显示名称
                    let displayName = MembershipLevel.getDisplayName(for: requiredLevel, language: "zh") ?? requiredLevel
                    let englishName = MembershipLevel.getDisplayName(for: requiredLevel, language: "en") ?? requiredLevel
                    statusText = "需要 \(displayName) 会员等级"
                    statusTextEn = "Requires \(englishName) Membership"
                } else {
                    statusText = "需要更高会员等级"
                    statusTextEn = "Higher membership level required"
                }
            case .outsideTimeSlot:
                    statusText = "不在运营时间，无法应用"
                    statusTextEn = "Outside business hours"
            case .usedThisWeek:
                statusText = "本周已用，下周自动解锁"
                statusTextEn = "Used this week, will unlock next week"
            case .notActivated:
                // 检查是否为.perOrder类型的已使用优惠券
                if coupon.usageFrequency == .perOrder,
                   let userCoupon = dataManager.currentUser?.ownedCoupons.first(where: { $0.couponCode == coupon.code }),
                   userCoupon.isUsed {
                    statusText = "已用，明日会再激活"
                    statusTextEn = "Used, will reactivate tomorrow"
                } else if let conditions = coupon.activationConditions {
                    statusText = conditions
                    if let conditionsEn = coupon.englishActivationConditions {
                        statusTextEn = conditionsEn
                    } else {
                        statusTextEn = "Not Activated"
                    }
                } else {
                    statusText = "未激活"
                    statusTextEn = "Not Activated"
                }
            default:
                statusText = "未激活"
                statusTextEn = "Not Activated"
            }
        }
        
        return AnyView(
            ZStack {
                baseCard
                    .opacity(0.6)
                
                // 统一的黑色半透明覆盖层
                RoundedRectangle(cornerRadius: 16)
                    .fill(Color.black.opacity(0.3))
                    .overlay(
                        VStack(spacing: 8) {
                            Image(systemName: "lock.fill")
                                .font(.system(size: 24))
                                .foregroundColor(.white)
                            
                            Text(dataManager.currentLanguage == "zh" ? statusText : statusTextEn)
                                .font(.system(size: 14, weight: .medium))
                                .foregroundColor(.white)
                                .multilineTextAlignment(.center)
                                .padding(.horizontal, 16)
                        }
                    )
            }
        )
    }
    

    
    // 获取按钮文本
    private func getButtonText(for coupon: Coupon, isDisabled: Bool) -> String {
        // 检查是否是会员信息完善礼券
        if coupon.code == "MEMBER_INFO_COMPLETE" {
            let hasUserCoupon = dataManager.currentUser?.ownedCoupons.contains { $0.couponCode == coupon.code && !$0.isUsed && $0.expiryDate > Date() } ?? false
            
            if hasUserCoupon {
                return dataManager.currentLanguage == "zh" ? "查看详情" : "View Details"
            } else if isDisabled {
                return dataManager.currentLanguage == "zh" ? "完善信息激活" : "Complete Info to Activate"
            }
        }
        
        if isDisabled {
            return dataManager.currentLanguage == "zh" ? "不可使用" : "Unavailable"
        }
        
        // 所有优惠券都显示"查看详情"
        return dataManager.currentLanguage == "zh" ? "查看详情" : "View Details"
    }
    
    // 为couponCard函数提供的按钮文本方法
    private func getButtonTextForCard(for title: String, isDisabled: Bool) -> String {
        // 检查是否是会员信息完善礼券
        if title.contains("完善会员信息") || title.contains("Complete Member Info") {
            let hasUserCoupon = dataManager.currentUser?.ownedCoupons.contains { $0.couponCode == "MEMBER_INFO_COMPLETE" && !$0.isUsed && $0.expiryDate > Date() } ?? false
            
            if hasUserCoupon {
                return dataManager.currentLanguage == "zh" ? "查看详情" : "View Details"
            } else if isDisabled {
                return dataManager.currentLanguage == "zh" ? "完善信息激活" : "Complete Info to Activate"
            }
        }
        
        if isDisabled {
            return dataManager.currentLanguage == "zh" ? "不可使用" : "Unavailable"
        }
        
        // 所有优惠券都显示"查看详情"
        return dataManager.currentLanguage == "zh" ? "查看详情" : "View Details"
    }
    
    // 处理按钮点击
    private func handleButtonTap(for coupon: Coupon) {
        // 检查用户是否已解锁此优惠券
        let isUnlocked = dataManager.isUserCouponUnlocked(coupon)
        
        if !isUnlocked {
            // 显示解锁条件提示
            var unlockMessage = ""
            
            if coupon.requiresLogin && dataManager.currentUser == nil {
                unlockMessage = dataManager.currentLanguage == "zh" ? "请先登录以解锁此优惠券" : "Please login to unlock this coupon"
            } else if let requiredLevelString = coupon.requiresMembershipLevel {
                // 根据requiresMembershipLevel（英文名称）找到对应的显示名称
                let displayName = MembershipLevel.getDisplayName(for: requiredLevelString, language: "zh") ?? requiredLevelString
                let englishName = MembershipLevel.getDisplayName(for: requiredLevelString, language: "en") ?? requiredLevelString
                unlockMessage = dataManager.currentLanguage == "zh" ? "需要达到 \(displayName) 会员等级" : "Requires \(englishName) membership level"
            } else {
                // 根据优惠券代码显示特定的解锁条件
                switch coupon.code {
                case "FUELUP_STREAK", "WEEKEND50", "HIGHBALL":
                    unlockMessage = dataManager.currentLanguage == "zh" ? "注册成为Level 1会员即可解锁" : "Register as Level 1 member to unlock"
                default:
                    unlockMessage = dataManager.currentLanguage == "zh" ? "满足特定条件后可解锁" : "Unlock after meeting specific conditions"
                }
            }
            
            alertMessage = unlockMessage
            showAlert = true
            return
        }
        
        // 检查是否是会员信息完善礼券
        if coupon.code == "MEMBER_INFO_COMPLETE" {
            let hasUserCoupon = dataManager.currentUser?.ownedCoupons.contains { $0.couponCode == coupon.code && !$0.isUsed && $0.expiryDate > Date() } ?? false
            let isMemberInfoComplete = dataManager.currentUser?.isMemberInfoComplete ?? false
            
            if !hasUserCoupon && !isMemberInfoComplete {
                // 如果用户没有完善信息，显示提示
                alertMessage = dataManager.currentLanguage == "zh" ? "请先完善会员信息以激活此优惠券" : "Please complete your member information to activate this coupon"
                showAlert = true
                return
            }
        }
        
        // 已解锁的优惠券显示详情弹窗
        selectedCoupon = coupon
    }
    
    // 动态礼券卡片组件
    private func dynamicCouponCard(coupon: Coupon, userCoupon: UserCoupon, status: CouponStatus) -> some View {
         let isExpiringSoon = false // 临时简化处理
         let isDisabled = status != .available
         let displayTitle = coupon.formattedTitle(language: dataManager.currentLanguage)
        
        return couponCard(
            tag: coupon.formattedTitle(language: dataManager.currentLanguage),
            tagColor: coupon.getTagColor(),
            tagTextColor: coupon.getTagTextColor(),
            buttonColor: coupon.getButtonColor(),
            buttonTextColor: coupon.getButtonTextColor(),
            value: coupon.formatValue(),
            title: coupon.formattedRemarks(language: dataManager.currentLanguage, displayTitle: displayTitle),
            validUntil: formatValidUntil(userCoupon: userCoupon, isExpiringSoon: isExpiringSoon, status: status),
            gradientColors: coupon.getGradientColors(),
            showStrikethrough: isDisabled,
            isDisabled: isDisabled,
            originalTitle: coupon.title,
            onButtonTap: {
                handleButtonTap(for: coupon)
            }
        )
    }
    

    

    

    // 格式化静态优惠券有效期
    private func formatStaticValidUntil(coupon: Coupon) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .none
        
        // 检查是否为长期有效优惠券（2070年以后的日期视为长期有效）
        let calendar = Calendar.current
        let year = calendar.component(.year, from: coupon.validUntil)
        
        if year >= 2070 {
            // 长期有效优惠券显示"N/A (长期有效)"
            return dataManager.currentLanguage == "zh" ? "N/A (长期有效)" : "N/A (Long-term valid)"
        } else {
            let validText = dataManager.currentLanguage == "zh" ? "有效期至 \(formatter.string(from: coupon.validUntil))" : "Valid until \(formatter.string(from: coupon.validUntil))"
            return validText
        }
    }
    
    // 格式化有效期
    private func formatValidUntil(userCoupon: UserCoupon, isExpiringSoon: Bool, status: CouponStatus) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .none
        
        // 根据状态显示不同信息
        switch status {
        case .expired:
            return dataManager.currentLanguage == "zh" ? "已过期" : "Expired"
        case .usedOnce:
            // 检查是否为perOrder类型的优惠券
            if let coupon = dataManager.getAllCouponsForDisplay().first(where: { $0.code == userCoupon.couponCode }),
               coupon.usageFrequency == .perOrder {
                return dataManager.currentLanguage == "zh" ? "已用，明日会再激活" : "Used, will reactivate tomorrow"
            } else {
                return dataManager.currentLanguage == "zh" ? "已使用" : "Used"
            }
        case .usedToday:
            return dataManager.currentLanguage == "zh" ? "今天已使用" : "Used Today"
        case .usedThisWeek:
            return dataManager.currentLanguage == "zh" ? "本周已使用" : "Used This Week"
        case .usedThisMonth:
            return dataManager.currentLanguage == "zh" ? "本月已使用" : "Used This Month"
        case .usedThisYear:
            return dataManager.currentLanguage == "zh" ? "今年已使用" : "Used This Year"
        case .outsideTimeSlot:
            return dataManager.currentLanguage == "zh" ? "不在适用时间" : "Outside Valid Time"
        case .notActivated:
            return dataManager.currentLanguage == "zh" ? "未激活" : "Not Activated"
        case .requiresLogin:
            return dataManager.currentLanguage == "zh" ? "需要登录" : "Login Required"
        case .requiresMembershipLevel:
            return dataManager.currentLanguage == "zh" ? "需要会员等级" : "Membership Level Required"
        case .available:
            // 检查是否为长期有效优惠券（2070年以后的日期视为长期有效）
            let calendar = Calendar.current
            let year = calendar.component(.year, from: userCoupon.expiryDate)
            
            if year >= 2070 {
                // 长期有效优惠券显示"N/A (长期有效)"
                return dataManager.currentLanguage == "zh" ? "N/A (长期有效)" : "N/A (Long-term valid)"
            } else {
                var validText = dataManager.currentLanguage == "zh" ? "有效期至 \(formatter.string(from: userCoupon.expiryDate))" : "Valid until \(formatter.string(from: userCoupon.expiryDate))"
                
                if isExpiringSoon {
                    let expiringText = dataManager.currentLanguage == "zh" ? " (即将到期)" : " (Expiring Soon)"
                    validText += expiringText
                }
                
                return validText
            }
        }
    }
    
    // 处理静态优惠券点击
    private func handleStaticCouponTap(coupon: Coupon) {
        // 静态优惠券点击处理 - 现在通过onTapGesture处理
        selectedCoupon = coupon
    }
    
    // 处理优惠券点击
    private func handleCouponTap(coupon: Coupon, userCoupon: UserCoupon, status: CouponStatus) -> Void {
        // 动态优惠券点击处理 - 现在通过onTapGesture处理
        selectedCoupon = coupon
    }
    
    // 生成适用时间提示信息
    private func generateTimeSlotMessage(coupon: Coupon) -> String {
        return dataManager.currentLanguage == "zh" ? "全天可用" : "Available all day"
    }
    
    // 获取渐变颜色
    private func getGradientColors(for type: Coupon.DiscountType) -> [Color] {
        switch type {
        case .percentage:
            return [
                Color(red: 1.0, green: 0.6, blue: 0.2),
                Color(red: 1.0, green: 0.5, blue: 0.1),
                Color(red: 0.9, green: 0.4, blue: 0.0)
            ]
        case .fixedAmount:
            return [
                Color(red: 0.4, green: 0.2, blue: 0.8),
                Color(red: 0.5, green: 0.3, blue: 0.9),
                Color(red: 0.3, green: 0.1, blue: 0.7)
            ]
        }
    }
    
    @ViewBuilder
    private func couponCard(
        tag: String,
        tagColor: Color,
        tagTextColor: Color,
        buttonColor: Color,
        buttonTextColor: Color,
        value: String,
        title: String,
        validUntil: String,
        gradientColors: [Color],
        showStrikethrough: Bool = false,
        isDisabled: Bool = false,
        quantity: Int? = nil,
        originalTitle: String,
        onButtonTap: (() -> Void)? = nil
    ) -> some View {
        let buttonBackgroundView = ZStack {
            // 3D立体效果背景
            Capsule()
                .fill(buttonColor)
                .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 2)
                .overlay(
                    Capsule()
                        .stroke(
                            LinearGradient(
                                colors: [
                                    Color.white.opacity(0.8),
                                    Color.clear
                                ],
                                startPoint: .top,
                                endPoint: .bottom
                            ),
                            lineWidth: 0.5
                        )
                )
            
            // 内部高光效果
            Capsule()
                .fill(
                    LinearGradient(
                        colors: [
                            Color.white.opacity(0.3),
                            Color.clear
                        ],
                        startPoint: .top,
                        endPoint: .center
                    )
                )
                .frame(height: 8)
                .offset(y: -2)
        }
         
         let mainBackgroundView = ZStack {
             // 主背景渐变
             RoundedRectangle(cornerRadius: 12)
                 .fill(
                     LinearGradient(
                         colors: isDisabled ? [Color.gray.opacity(0.6), Color.gray.opacity(0.4)] : gradientColors,
                         startPoint: .topLeading,
                         endPoint: .bottomTrailing
                     )
                 )
             
             // 3D立体效果
             RoundedRectangle(cornerRadius: 12)
                 .stroke(
                     LinearGradient(
                         colors: [
                             Color.white.opacity(0.3),
                             Color.clear,
                             Color.black.opacity(0.1)
                         ],
                         startPoint: .topLeading,
                         endPoint: .bottomTrailing
                     ),
                     lineWidth: 1
                 )
             
             // 内部高光
             RoundedRectangle(cornerRadius: 11)
                 .fill(
                     LinearGradient(
                         colors: [
                             Color.white.opacity(0.15),
                             Color.clear
                         ],
                         startPoint: .top,
                         endPoint: .center
                     )
                 )
                 .padding(1)
         }
         .shadow(color: .black.opacity(0.2), radius: 6, x: 0, y: 3)
         .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)
         
         VStack(alignment: .leading, spacing: 3) {
            HStack {
                HStack(spacing: 4) {
                    Text(tag)
                        .font(.caption2)
                        .fontWeight(.bold)
                        .foregroundColor(tagTextColor)
                        .padding(.horizontal, 4)
                        .padding(.vertical, 1)
                        .background(Capsule().fill(tagColor))
                    
                    // 根据配置决定特定现金券的徽章位置
                    let shouldShowBadgeAdjacentToTag = AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[tag] == .adjacentToTag || 
                                                      AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[originalTitle] == .adjacentToTag
                    
                    // 调试信息：打印实际的tag和originalTitle值
                    let _ = {
                        if originalTitle.contains("Cash Voucher") || originalTitle.contains("现金券") {
                            // 现金券徽章位置计算
                        }
                    }()
                    if let quantity = quantity, quantity > 0, shouldShowBadgeAdjacentToTag {
                        Text("\(quantity)")
                            .font(.caption2)
                            .fontWeight(.bold)
                            .foregroundColor(.white)
                            .padding(AppConfig.CashVoucher.Layout.quantityBadgeSize)
                            .background(
                                Circle()
                                    .fill(
                                        LinearGradient(
                                            colors: [
                                                Color.red,
                                                Color.red.opacity(0.8)
                                            ],
                                            startPoint: .top,
                                            endPoint: .bottom
                                        )
                                    )
                                    .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 1)
                            )
                    }
                }
                
                Spacer()
                
                // 特定现金券金额文字特殊处理：向左偏移避免被数字标识遮挡
                let shouldOffsetValueText = AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[tag] == .adjacentToTag || 
                                           AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[originalTitle] == .adjacentToTag
                
                // 调试信息：打印右上角徽章的相关信息
                let _ = {
                    if originalTitle.contains("Cash Voucher") || originalTitle.contains("现金券") {
                        // 右侧徽章位置计算
                    }
                }()
                
                Text(value)
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(CouponTheme.getCouponType(from: originalTitle).textColor)
                    .strikethrough(showStrikethrough, color: CouponTheme.getCouponType(from: originalTitle).textColor)
                    .offset(x: shouldOffsetValueText && quantity != nil ? AppConfig.CashVoucher.Layout.valueTextLeftOffset : 0)
            }
            
            Text(title)
                .font(.caption2)
                .fontWeight(.semibold)
                .foregroundColor(CouponTheme.getCouponType(from: originalTitle).textColor)
                .lineLimit(1)
                .multilineTextAlignment(.leading)
            
            VStack(alignment: .leading, spacing: 2) {
                HStack {
                    Text(validUntil)
                        .font(.caption2)
                        .foregroundColor(CouponTheme.getCouponType(from: originalTitle).subtitleColor)
                        .lineLimit(1)
                    
                    Spacer()
                    
                    Button(action: {
                        onButtonTap?()
                    }) {
                        Text(getButtonTextForCard(for: title, isDisabled: isDisabled))
                            .font(.caption2)
                            .fontWeight(.bold)
                            .foregroundColor(buttonTextColor)
                            .padding(.horizontal, 8)
                            .padding(.vertical, 3)
                            .background(buttonBackgroundView)
                    }
                    .disabled(isDisabled)
                    .scaleEffect(isDisabled ? 0.9 : 1.0)
                    .opacity(isDisabled ? 0.6 : 1.0)
                }
            }
        }
        .padding(8)
        .frame(height: 76) // 统一高度与HomeView保持一致
        .frame(maxWidth: .infinity)
        .background(mainBackgroundView)
        .overlay(
            // 数量角标（仅对非特定现金券显示在右上角）
            Group {
                if let quantity = quantity, quantity > 0 {
                    // 调试信息：打印右上角徽章的显示条件
                    let shouldShowInTopRight = AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[tag] != .adjacentToTag && 
                                              AppConfig.CashVoucher.Layout.specificVoucherBadgePositions[originalTitle] != .adjacentToTag
                    
                    let _ = {
                        if originalTitle.contains("Cash Voucher") || originalTitle.contains("现金券") {
                            // 右上角徽章位置计算
                        }
                    }()
                    if shouldShowInTopRight {
                        VStack {
                            HStack {
                                Spacer()
                                Text("\(quantity)")
                                    .font(.caption2)
                                    .fontWeight(.bold)
                                    .foregroundColor(.white)
                                    .padding(AppConfig.CashVoucher.Layout.quantityBadgeSize)
                                    .background(
                                        Circle()
                                            .fill(
                                                LinearGradient(
                                                    colors: [
                                                        Color.red,
                                                        Color.red.opacity(0.8)
                                                    ],
                                                    startPoint: .top,
                                                    endPoint: .bottom
                                                )
                                            )
                                            .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 1)
                                    )
                                    .offset(x: -8, y: AppConfig.CashVoucher.Layout.quantityBadgeTopOffset)
                            }
                            Spacer()
                        }
                    }
                }
            }
        )
        .opacity(isDisabled ? 0.7 : 1.0)
    }
}



#Preview {
    CouponsView()
        .environmentObject(DataManager.shared)
}